<!--
*@description   模板审核列表
*@fileName tplReview.vue
!-->
<template>
  <!-- 列表 -->
  <ContentWrap class="full-height">
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #toolbarButtons>
        <el-radio-group v-model="queryParams.reviewStatus" size="large" >
          <el-radio-button 
            :value="item.value" 
            :label="item.name" 
            v-for="(item,index) in reStatusList" 
            :key="index"
            @change="reviewStatusChange"
            >
          </el-radio-button>
        </el-radio-group>
      </template>
      <template #type="{ row }">
        <dict-tag :type="DICT_TYPE.CONTRACT_TYPE" :value="row.type" />
      </template>
      <template #reviewResp="{ row }">
        <div v-for="(item,index) in row.reviewRespVOS" :key="index">
        {{item.reviewName}} -  [{{item.status == 0 ? '待审核' : (item.status === 1 ? '审核通过' : '审核拒绝')}}] 
        </div>
      </template>
      <template #operate="{ row }">
        <el-button type="danger" size="small" @click="handleReview(row.tplNo,row.id)" v-hasPermi="['ctr:tpl:review']" plain>审核</el-button>
      </template>
    </vxe-grid>
  </ContentWrap>


  <!-- 搜索抽屉 -->
  <SearchDrawer ref="searchRef" v-model="queryParams" @search="getList" />

  <!-- 模板审核弹窗 -->
  <reviewDialog ref="reviewDialogRef" @success="getList"></reviewDialog>
</template>

<script setup lang="ts">
import {getTplPage} from '@/api/contract/tplReview'
import type { VxeGridProps, VxeGridListeners,VxeGridInstance  } from 'vxe-table'
import { DICT_TYPE } from '@/utils/dict'
import SearchDrawer from './SearchDrawer.vue'
import {formatToDateTime} from '@/utils/dateUtil'
import reviewDialog from './reviewDialog.vue'

defineOptions({ name: 'tplReview' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  reviewStatus: ''
})
/* 
模板tab选择
 "审核状态 0待审核 1 审核通过(所有租户都审核通过)")
*/
const reStatusList = ref([{
  name: '全部',
  value: ''
},{
  name: '待审核',
  value: 0
},{
  name: '审核通过',
  value: 1
}])
const searchRef = ref()
// 表格实例
const gridRef = ref<VxeGridInstance>()
const reviewDialogRef = ref()

// 调用vxe grid query方法重载表格
const getList = () => {
  if (gridRef.value) {
    gridRef.value.commitProxy('query') // 触发表格重新加载数据
  }
}
// 获取表格数据
const fetchApi = () => {
  return new Promise(async (resolve) => {
    try {
      const res = await getTplPage(queryParams)
      gridOptions.data = res.list
      resolve({
        page: {
          total: res.total
        },
        result: res.list
      })
      
    } catch (error) {
      resolve({
        page: {
          total: 0
        },
        result: []
      })
      console.log('error',error)
    }
  })
}

// 模拟后台接口
// const delApi = (removeRecords: DatasourceVO[]) => {
//   return new Promise(async (resolve, reject) => {
//     try{
//       let ids = removeRecords.map((item) => item.id).join(',')
//       await DatasourceApi.deleteDatasources(ids)
//       setTimeout(() => {
//         resolve({
//           result: [],
//           msg: `delete，${removeRecords.length}条`
//         })
//       }, 100)
//     }catch (e) {
//       reject(e)
//     }
//   })
// }

const gridOptions = reactive<VxeGridProps<any>>({
  stripe: true,
  border: true,
  keepSource: true,
  height: '100%',
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },
  toolbarConfig: {
    import: false,
    export: false,
    print: false,
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbarButtons'
    },
    tools: [
      { name: '', code: 'search', icon: 'vxe-icon-search', status: 'info' }
    ]
  },
  proxyConfig: {
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      // 接收 Promise
      query: ({ page }) => {
        queryParams.pageNo = page.currentPage
        queryParams.pageSize = page.pageSize
        return fetchApi()
      },
      // body 对象： { removeRecords }
      // delete: ({ body }) => {
      //   // return delApi(body.removeRecords)
      // }
    }
  },
  columns: [
    { type: 'seq', width: 70 },
    { field: 'tplNo', title: '模板编码', minWidth: '250px' },
    { field: 'name', title: '模板名称', minWidth: '100px' },
    { field: 'type', title: '模板类型', minWidth: '100px',slots: { default: 'type' } },
    
    // { field: 'driverClass', title: '驱动', minWidth: '100px' },
    { field: 'reviewResp', title: '审核进度', minWidth: '100px',slots: { default: 'reviewResp' } },
    { field: 'createTime', title: '生效日期', minWidth: '100px',
      formatter: ({row}: any) => {
        return formatToDateTime(row.createTime)
      }
     },
    { field: 'reviewStatus', title: '状态', minWidth: '100px',
      formatter: ({row}: any) => {
        return row.reviewStatus == 0 ? '待审核' : (row.reviewStatus === 1 ? '审核通过' : '审核拒绝')
      }
     },
    { title: '操作', width: 80, slots: { default: 'operate' } }
  ],
  data: []
})

const gridEvents: VxeGridListeners = {
  toolbarButtonClick(params) {
    console.log(params.code)
  },

  toolbarToolClick({ code }) {
    // console.log(123, code, tool)
    switch (code) {
      case 'search':
        handelSearch()
        break
      case 'del':
        if (gridRef.value) {
          gridRef.value.commitProxy('delete')
        }
        break
    }
  }
}
// 头部审核状态切换
const reviewStatusChange = (value: number) => {
  console.log(value)
  fetchApi()
}
const handelSearch = () => {
  searchRef.value?.open()
}

/** 审核 */
const handleReview = async (tplNo: string,id: number) => {
  reviewDialogRef.value?.open(tplNo,id)
}
</script>

